package com.ly.system.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ly.common.core.bean.R;
import com.ly.common.core.constant.TokenConstants;
import com.ly.common.core.tool.security.utils.TokenUtils;
import com.ly.common.core.utils.BaseUtils;
import com.ly.common.core.utils.RedisUtils;
import com.ly.system.service.ISysUserService;
import com.ly.system.system.bean.entity.SysUser;
import com.ly.system.system.bean.vo.SysUserOnlineVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * 在线用户
 *
 * @author luoyun
 * @Date: 2020-06-07
 */
@Slf4j
@RestController
@RequestMapping("/sys/online")
@RequiredArgsConstructor
public class SysUserOnlineController {

    private final RedisUtils redisUtils;
    private final ISysUserService sysUserService;

    @GetMapping("/getPage")
    public R<Page<SysUserOnlineVO>> getPage(@RequestParam(name = "username", required = false) String username,
                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Collection<String> keys = redisUtils.scan(TokenConstants.LOGIN_TOKEN_KEY + "*");
        if (CollUtil.isEmpty(keys)) {
            return R.ok();
        }
        List<SysUserOnlineVO> onlineList = new ArrayList<>();
        for (String key : keys) {
            String token = StrUtil.replace(key, TokenConstants.LOGIN_TOKEN_KEY, "");
            if (StrUtil.isNotEmpty(token)) {
                SysUserOnlineVO online = new SysUserOnlineVO();
                online.setToken(token);
                // TODO 改成一次性查询
                String tokenUserName = BaseUtils.getUsername();
                if (StrUtil.isEmpty(username) || username.equals(tokenUserName)) {
                    SysUser sysUser = sysUserService.getUserByName(tokenUserName);
                    BeanUtils.copyProperties(sysUser, online);
                    onlineList.add(online);
                }
            }
        }
        Collections.reverse(onlineList);
        Page<SysUserOnlineVO> page = new Page<SysUserOnlineVO>(pageNo, pageSize);
        int count = onlineList.size();
        List<SysUserOnlineVO> pages = new ArrayList<>();
        // 计算当前页第一条数据的下标
        int currId = pageNo > 1 ? (pageNo - 1) * pageSize : 0;
        for (int i = 0; i < pageSize && i < count - currId; i++) {
            pages.add(onlineList.get(currId + i));
        }
        page.setSize(pageSize);
        page.setCurrent(pageNo);
        page.setTotal(count);
        // 计算分页总页数
        page.setPages(count % 10 == 0 ? count / 10 : count / 10 + 1);
        page.setRecords(pages);
        return R.ok(page);
    }

    /**
     * 强退用户
     */
    @PostMapping("/forceLogout")
    public R<String> forceLogout(@RequestBody SysUserOnlineVO online) {
        // 用户退出逻辑
        String token = online.getToken();
        if (StrUtil.isEmpty(token)) {
            return R.fail("退出登录失败！");
        }
        String uuid = BaseUtils.getUuidByToken(token);
        TokenUtils.delLoginUser(uuid);
        log.info(" 用户强制退出成功： 操作人：{} 当前token：{}", BaseUtils.getRealname(), token);
        return R.ok("退出登录成功！");
    }
}
